# coding=utf-8

from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# MySQL数据库配置
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:123456@localhost:3306/test'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

# 创建数据库对象
db = SQLAlchemy(app)


# 模型要继承db.Model
class Author(db.Model):
    # 表名为__tablename__
    __tablename__ = 'T_AUTHOR'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

    # 关系引用，非持久化字段,backref中的author是后续给Book使用的
    books = db.relationship('Book', backref='author')

    def __repr__(self):
        return 'Author: %s' % self.name


class Book(db.Model):
    __tablename__ = 'T_BOOK'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))

    # 外键引用
    author_id = db.Column(db.Integer, db.ForeignKey('T_AUTHOR.id'))

    def __repr__(self):
        return 'Book: %s' % self.name


@app.route('/index')
def index():
    return render_template('books.html')


if __name__ == '__main__':
    app.run()
